package learningThread.threadPool.reject;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 将"线程池的拒绝策略"由DiscardPolicy修改为DiscardOldestPolicy之后，当有任务添加到线程池被拒绝时，
 * 线程池会丢弃阻塞队列中末尾的任务，然后将被拒绝的任务添加到末尾。
 */
public class TestDiscardOldestPolicy {

    private static final int THREADS_SIZE = 3;
     private static final int CAPACITY = 3;

    public static void main(String[] args) {
            ThreadPoolExecutor pool = new ThreadPoolExecutor(THREADS_SIZE, THREADS_SIZE,
                    0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(CAPACITY));

            // 设置线程池的拒绝策略为"丢弃"
            pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());

            TestAborstPolicy testAborstPolicy = new TestAborstPolicy();

            // 新建10个任务，并将它们添加到线程池中。
            for (int i = 0; i < 10; i++) {
                TestAborstPolicy.MyRunnable myrun =testAborstPolicy.new MyRunnable("task-"+i);
                //pool.execute(myrun);
                pool.submit(myrun);
            }

            // 关闭线程池
            pool.shutdown();
        }
    }

